<template>
  <div class="shop-list">
    <div class="page-header">
      <h2>店铺管理</h2>
      <el-button type="primary" @click="handleAdd">添加店铺</el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="店铺名称">
        <el-input v-model="searchForm.shop_name" placeholder="请输入店铺名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="地区">
        <el-input v-model="searchForm.region" placeholder="请输入地区" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 店铺列表表格 -->
    <el-table
      v-loading="loading"
      :data="shopList"
      border
      style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="shop_name" label="店铺名称"></el-table-column>
      <el-table-column prop="shop_address" label="店铺地址" show-overflow-tooltip></el-table-column>
      <el-table-column prop="provincia_level_name" label="省份"></el-table-column>
      <el-table-column prop="municipa_level_name" label="城市"></el-table-column>
      <el-table-column prop="district_level_name" label="区县"></el-table-column>
      <el-table-column prop="item_count" label="商品数量" width="100"></el-table-column>
      <el-table-column prop="enabled" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.enabled === '启用' ? 'success' : 'info'">
            {{ row.enabled }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            size="small"
            @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="primary"
            @click="handleViewProducts(row)">查看商品</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑店铺对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="shopForm" :rules="rules" ref="shopFormRef" label-width="100px">
        <el-form-item label="店铺名称" prop="shop_name">
          <el-input v-model="shopForm.shop_name"></el-input>
        </el-form-item>
        <el-form-item label="店铺地址" prop="shop_address">
          <el-input v-model="shopForm.shop_address"></el-input>
        </el-form-item>
        <el-form-item label="省份" prop="provincia_level_name">
          <el-input v-model="shopForm.provincia_level_name"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="municipa_level_name">
          <el-input v-model="shopForm.municipa_level_name"></el-input>
        </el-form-item>
        <el-form-item label="区县" prop="district_level_name">
          <el-input v-model="shopForm.district_level_name"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-select v-model="shopForm.enabled" placeholder="请选择状态">
            <el-option label="启用" value="启用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getShopList, createShop, updateShop, deleteShop } from '@/api/shop'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ShopList',
  setup() {
    const loading = ref(false)
    const retryCount = ref(0)
    const maxRetries = 3
    const shopList = ref([])
    const searchForm = ref({
        shop_name: '',
        region: ''
    })
    const page = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const shopFormRef = ref(null)
    const shopForm = ref({
      id: null,
        shop_name: '',
        shop_address: '',
        provincia_level_name: '',
        municipa_level_name: '',
        district_level_name: '',
      enabled: '启用'
    })
    const rules = {
        shop_name: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        shop_address: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' }
        ]
      }

    // 在组件挂载时获取数据
    onMounted(() => {
      fetchData()
    })

    async function fetchData() {
      loading.value = true
      try {
        const params = {
          page: page.value,
          pageSize: pageSize.value,
          shop_name: searchForm.value.shop_name,
          region: searchForm.value.region
        }
        const response = await getShopList(params)
        if (response && response.items) {
          shopList.value = response.items
          total.value = response.total
          retryCount.value = 0  // 重置重试计数
        } else {
          shopList.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取店铺列表失败:', error)
        if (retryCount.value < maxRetries) {
          retryCount.value++
          setTimeout(() => {
            fetchData()
          }, 1000 * retryCount.value)  // 递增延迟
        } else {
          ElMessage.error('获取店铺列表失败，请稍后重试')
          shopList.value = []
          total.value = 0
      }
      } finally {
        loading.value = false
      }
    }

    function handleSearch() {
      page.value = 1
      retryCount.value = 0  // 重置重试计数
      fetchData()
    }

    function resetSearch() {
      searchForm.value = {
        shop_name: '',
        region: ''
      }
      page.value = 1
      pageSize.value = 10
      retryCount.value = 0  // 重置重试计数
      fetchData()
    }

    function handleSizeChange(val) {
      pageSize.value = val
      page.value = 1
      retryCount.value = 0  // 重置重试计数
      fetchData()
    }

    function handleCurrentChange(val) {
      page.value = val
      retryCount.value = 0  // 重置重试计数
      fetchData()
    }

    function handleAdd() {
      dialogTitle.value = '添加店铺'
      shopForm.value = {
        id: null,
        shop_name: '',
        shop_address: '',
        provincia_level_name: '',
        municipa_level_name: '',
        district_level_name: '',
        enabled: '启用'
      }
      dialogVisible.value = true
    }

    function handleEdit(row) {
      dialogTitle.value = '编辑店铺'
      shopForm.value = {
        id: row.id,
        shop_name: row.shop_name,
        shop_address: row.shop_address,
        provincia_level_name: row.provincia_level_name,
        municipa_level_name: row.municipa_level_name,
        district_level_name: row.district_level_name,
        enabled: row.enabled
      }
      dialogVisible.value = true
    }

    function handleViewProducts(row) {
      // Implementation of handleViewProducts
    }

    async function handleDelete(row) {
      try {
        await ElMessageBox.confirm('确认删除该店铺吗？', '提示', {
          type: 'warning'
        })
        await deleteShop(row.id)
        ElMessage.success('删除成功')
        fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除店铺失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    async function submitForm() {
      if (!shopFormRef.value) return
      
      try {
        // 表单验证
        await shopFormRef.value.validate()
        
        if (shopForm.value.id) {
          // 更新店铺
          await updateShop(shopForm.value.id, shopForm.value)
          ElMessage.success('更新成功')
            } else {
          // 创建店铺
          await createShop(shopForm.value)
          ElMessage.success('创建成功')
            }
        dialogVisible.value = false
        fetchData() // 刷新列表
          } catch (error) {
        if (error === false) {
          // 表单验证失败
          return
        }
        console.error('提交店铺信息失败:', error)
        ElMessage.error('提交失败')
          }
        }

    return {
      loading,
      shopList,
      searchForm,
      page,
      pageSize,
      total,
      dialogVisible,
      dialogTitle,
      shopForm,
      rules,
      shopFormRef,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleViewProducts,
      handleDelete,
      submitForm
    }
  }
}
</script>

<style scoped>
.shop-list {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 